package com.webjavamail.servlets;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

public class SendAttachmentMailServlet extends HttpServlet {

	private static final long serialVersionUID = 686051362689871451L;
	private ServletContext sc;
	private String savePath;
	private Map<String,String> parameters=new HashMap<String,String> ();	
	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		File file=this.doAttachment(request);
		MultiPartEmail email=new MultiPartEmail();
		email.setCharset("utf-8");
		email.setHostName("smtp.sina.com");
		email.setAuthentication("jqbhesn@sina.com", "xiaodong");
		try {
			email.setFrom(parameters.get("from"));
			email.addTo(parameters.get("to"));
			email.setSubject(parameters.get("title"));
			email.setMsg(parameters.get("content"));
			if(file!=null){
				EmailAttachment attachment =new EmailAttachment();
				attachment.setPath(file.getPath());//附件的路经
				attachment.setDisposition(EmailAttachment.ATTACHMENT);//附件的类型
				attachment.setName(file.getName());
				email.attach(attachment);
			}
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功！");
		} catch (EmailException e) {
			e.printStackTrace();
			request.setAttribute("sendmail.message", "邮件发送失败！");
		}
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);
	}

	@SuppressWarnings("rawtypes")
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		request.setCharacterEncoding("utf-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();// FileItem可以包含文件或文本信息
				if (item.isFormField()) {// 判断是否是文本信息
//				System.out.println("表单的参数名称：" + item.getFieldName()
//							+ "，对应的参数值： " + item.getString("utf-8"));
					parameters.put(item.getFieldName(), item.getString("utf-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						File tempFile = new File(item.getName());
						file = new File(sc.getRealPath("/") + savePath,
								tempFile.getName());// 当前应用的真实物理路经
						item.write(file);
					} 
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("upload.message", "上传文件失败！");
		}
		return file;
	}

	public void init(ServletConfig config) {
		this.savePath = config.getInitParameter("savePath");
		this.sc = config.getServletContext();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
